#!/usr/bin/env node

const mysql = require('mysql2/promise');
const {con,ResData} = require('./common');
const fs = require('fs'),
      path = require('path');

async function postPicture(files){
  let filesArr = [];
  if(!files.length){
    filesArr.push(files);
  }else{
    filesArr = files;
  }
  const res = new ResData();
  for(let item of filesArr){
    //判断上传文件类型
    if(!/image\/(gif|jpg|jpeg|png|GIF|JPG|bmp)$/.test(item.mimetype)){
      if(item.originalFilename == ''){
        res.msg = '未上传文件，请选择文件后上传!';
      }else{
        let name = item.originalFilename;
        res.msg = `${res.msg}${name}:上传的不是图片,上传失败！`;
      }
    }else{
      //读取图片并写入upload文件夹内
      let dirname = path.resolve(__dirname,'..');
      //没有upload文件夹创建
      let _dirpath = dirname + path.join('/upload');
      if(!fs.existsSync(_dirpath)){
        fs.mkdirSync(_dirpath);                                
      }        
      const reader = fs.createReadStream(item.filepath);
      let filepath = dirname + path.join('/upload')+`/${item.newFilename}`;
      const writer = fs.createWriteStream(filepath);
      reader.pipe(writer);
      //存入数据库
      let src = filepath;
      let name = item.originalFilename;
      let sql = `insert into pictures(name,src) values("${name}","${src}")`;
      try{
        let [rows] = await con.execute(sql);
        res.msg = rows.affectedRows === 1 ? 
          `${res.msg}${name}:上传成功 `:`${res.msg}${name}:上传失败 `;
      }catch(e){
        res.code = 401001;
        res.msg = `${res.msg}${name}:上传失败 `;
      } 
    }
  } 
  return res.msg;
}

async function getCount(){
  const res = new ResData();
  //获取图片总数
  let sqlCount='select count(id) as count from pictures;';
  let [rows] = await con.query(sqlCount);
  res.count = rows[0].count; 
  return res;
}

async function showPagePicture(page=1,limit=10){
  const res = new ResData();
  //从数据库中获取图片信息
  let sql = `select * from pictures order by id limit ${(page-1)*limit},${limit}`,
    sqlCount='select count(id) as count from pictures;';
  let [rows] = await con.query(sql);
  for(let item of rows){
    let file = fs.readFileSync(item.src);
    let base = file.toString('base64');
    let url='data:image/png;base64,'+base;
    item.src = url;
  }
  res.data = rows;  
  [rows] = await con.query(sqlCount);
  res.count = rows[0].count;     
  return res;
}

async function deletePicture(id){
  const res = new ResData();
  //获取删除图片的路径
  let sql =`select * from pictures where id=${id}`;
  let [rows] = await con.execute(sql);
  let path = rows[0].src;
  //删除upload文件夹存储的图片
  fs.unlink(path,function(error){
      if(error){
        return false;   
        console.log("error");
      }
      console.log('删除文件成功');
    })
  //删除数据库中文件
  let delsql = `delete from pictures where id=${id}`;
  try{
    [rows] = await con.execute(delsql);
    res.msg = rows.affectedRows === 1?'ok':'delete failed';
  }catch(e){
    res.code = 401002;
    res.msg = 'delete failed';
  }
  return res;
}

module.exports = {
  postPicture,
  getCount,
  showPagePicture,
  deletePicture
};
